import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 如果正确读取帧，ret为True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # 我们在框架上的操作到这里
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    # 3.实例化OpenCV人脸识别的分类器
    face_cas = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
    face_cas.load('haarcascade_frontalface_default.xml')
    # 4.调用识别人脸
    faceRects = face_cas.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

    for faceRect in faceRects:
        x, y, w, h = faceRect
        # 框出人脸
        cv.rectangle(frame, (x, y), (x + h, y + w), (0, 255, 0), 3)
    cv.imshow("frame", frame)
    # # 显示结果帧e
    # cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# 完成所有操作后，释放捕获器
cap.release()
cv.destroyAllWindows()
